/*
 * input.c
 *
 *  Created on: 2012/09/19
 *      Author: softwareDeveloper
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "typedef.h"
#include "Id.h"
#include "rule_if.h"
#include "rule_inout.h"

INPUTINFO stInputInfo;
static CHAR lineBuf[OS_FULLPATH];

static BOOL checkSpaceLine(PSZ line) {
	int i = 0;
	strcpy(lineBuf, line);
	while (lineBuf[i] != '\0') {
		if (lineBuf[i] != ' ' && lineBuf[i] != '\t') {
			return FALSE;
		}
		i++;
	}
	return TRUE;
}

INT analyzeInput(PSZ path, PSZ workspace) {
	FILE * file;
	BOOL bIn = FALSE;
	BOOL bOut_ENG = FALSE;
	BOOL bOut_CHS = FALSE;
	BOOL bOut_JPN = FALSE;
	BOOL bRule = FALSE;

	file = fopen(path, "r");
	if (file == NULL ) {
		printf("can not open file %s\n", path);
		return EXIT_ERROR;
	}

	while (fgets(lineBuf, OS_FULLPATH - 1, file) != NULL ) {
		lineBuf[strlen(lineBuf) - 1] = '\0';
		if(lineBuf[strlen(lineBuf) - 1] == '\r'){
			lineBuf[strlen(lineBuf) - 1] = '\0';
		}
		if (lineBuf[0] != '#') {
			if (bIn) {
				stInputInfo.inDbPath = (PSZ) malloc(
						sizeof(workspace) + sizeof(lineBuf) + 1);
				strcpy(stInputInfo.inDbPath, workspace);
				strcat(stInputInfo.inDbPath, lineBuf);
				bIn = FALSE;
			} else if (bOut_ENG) {
				stInputInfo.inOutMsgEng = (PSZ) malloc(
						sizeof(workspace) + sizeof(lineBuf) + 1);
				strcpy(stInputInfo.inOutMsgEng, workspace);
				strcat(stInputInfo.inOutMsgEng, lineBuf);
				bOut_ENG = FALSE;
			} else if (bOut_CHS) {
				stInputInfo.inOutMsgChs = (PSZ) malloc(
						sizeof(workspace) + sizeof(lineBuf) + 1);
				strcpy(stInputInfo.inOutMsgChs, workspace);
				strcat(stInputInfo.inOutMsgChs, lineBuf);
				bOut_CHS = FALSE;
			} else if (bOut_JPN) {
				stInputInfo.inOutMsgJpn = (PSZ) malloc(
						sizeof(workspace) + sizeof(lineBuf) + 1);
				strcpy(stInputInfo.inOutMsgJpn, workspace);
				strcat(stInputInfo.inOutMsgJpn, lineBuf);
				bOut_JPN = FALSE;
			} else if (bRule) {
				if (checkSpaceLine(lineBuf)) {
					bRule = FALSE;
				} else {
					stInputInfo.hasRule = TRUE;
					AddSelRule(lineBuf);
				}
			} else if (!strcmp(lineBuf, "[IN-SQList]")) {
				bIn = TRUE;
			} else if (!strcmp(lineBuf, "[OUTPUT_ENG]")) {
				bOut_ENG = TRUE;
			} else if (!strcmp(lineBuf, "[OUTPUT_CHS]")) {
				bOut_CHS = TRUE;
			} else if (!strcmp(lineBuf, "[OUTPUT_JPN]")) {
				bOut_JPN = TRUE;
			} else if (!strcmp(lineBuf, "[RULES]")) {
				bRule = TRUE;
			}
		}
	}
	fclose(file);
	return EXIT_SUCCESS;
}

INT freeIO(VOID) {
	free(stInputInfo.inDbPath);
	free(stInputInfo.inOutMsgEng);
	free(stInputInfo.inOutMsgChs);
	free(stInputInfo.inOutMsgJpn);
	stInputInfo.inDbPath = NULL;
	stInputInfo.inOutMsgEng = NULL;
	stInputInfo.inOutMsgChs = NULL;
	stInputInfo.inOutMsgJpn = NULL;
	return EXIT_SUCCESS;
}

